package cc.site.main.controller;

import cc.site.common.utils.R;
import cc.site.main.bean.TblRoom;
import cc.site.main.bean.dto.PetDto;
import cc.site.main.bean.vo.RoomVo;
import cc.site.main.service.TblPetService;
import cc.site.main.service.TblRoomService;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 房间 前端控制器
 * </p>
 *
 * @author yangruomao
 * @since 2024-04-14
 */
@RestController
@RequestMapping("/room")
@Api(tags = "房间管理")
public class TblRoomController {

    @Autowired
    private TblRoomService roomService;

    @Autowired
    private TblPetService petService;

    @PostMapping
    @ApiOperation("添加房间信息")
    public R save(@Valid @RequestBody RoomVo vo) {
        TblRoom room = new TblRoom();
        BeanUtil.copyProperties(vo, room);
        if (roomService.save(room)) {
            return R.ok().message("添加房间信息成功");
        } else {
            return R.error().message("添加房间信息失败");
        }
    }

    @DeleteMapping("/{roomId}")
    @ApiOperation("删除指定ID的房间信息")
    public R delete(@PathVariable("roomId") Integer roomId) {
        // 查询这个room下有多少个宠物
        if (roomService.getPetCountByRoomId(roomId) > 0) {
            return R.error().message("该房间下有宠物，不能删除");
        }

        if (roomService.removeById(roomId)) {
            return R.ok().message("删除房间信息成功");
        } else {
            return R.error().message("删除房间信息失败");
        }
    }

    @PutMapping
    @ApiOperation("更新房间信息")
    public R update(Integer roomId ,@Valid @RequestBody RoomVo vo) {
        TblRoom room = roomService.getById(roomId);
        BeanUtils.copyProperties(vo, room);
        if (roomService.updateById(room)) {
            return R.ok().message("更新房间信息成功");
        } else {
            return R.error().message("更新房间信息失败");
        }
    }

    @GetMapping("/{page}/{limit}")
    @ApiOperation("分页查询房间信息，page从1开始，limit为每页数量")
    public R list(@PathVariable("page") Integer page, @PathVariable("limit") Integer limit) {
        Page<TblRoom> roomsPage = roomService.page(new Page<>(page, limit), null);
        return R.ok().data("page", roomsPage);
    }

}
